﻿import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import HomeView from "../views/HomeView.vue";
import RecipesView from "../views/RecipesView.vue";
import GuidesView from "../views/GuidesView.vue";
import ProfileView from "../views/ProfileView.vue";
import ArticleDetailView from "../views/ArticleDetailView.vue";
import LoginView from "../views/LoginView.vue";
import RegisterView from "../views/RegisterView.vue";
import AdminView from "../views/AdminView.vue";
import { useContentStore } from "../stores/content";
import { useAuthStore } from "../stores/auth";

const routes: RouteRecordRaw[] = [
  { path: "/", name: "home", component: HomeView },
  { path: "/recipes", name: "recipes", component: RecipesView },
  { path: "/guides", name: "guides", component: GuidesView },
  {
    path: "/profile",
    name: "profile",
    component: ProfileView,
    meta: { requiresAuth: true },
  },
  {
    path: "/articles/:id",
    name: "article-detail",
    component: ArticleDetailView,
    props: true,
  },
  {
    path: "/login",
    name: "login",
    component: LoginView,
    meta: { standalone: true },
  },
  {
    path: "/register",
    name: "register",
    component: RegisterView,
    meta: { standalone: true },
  },
  {
    path: "/admin",
    name: "admin",
    component: AdminView,
    meta: { requiresAuth: true, requiresAdmin: true },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return { top: 0 };
  },
});

router.beforeEach(async (to) => {
  const contentStore = useContentStore();
  const authStore = useAuthStore();

  if (!contentStore.isHydrated) {
    await contentStore.bootstrap();
  }

  if (authStore.isAuthenticated && (to.name === "login" || to.name === "register")) {
    return { name: "home" };
  }

  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    return {
      name: "login",
      query: { redirect: to.fullPath },
    };
  }

  if (to.meta.requiresAdmin && !authStore.isAdmin) {
    return { name: "home" };
  }

  if (to.name === "profile" && authStore.isAdmin) {
    return { name: "admin" };
  }

  if (to.name === "article-detail") {
    const articleId = String(to.params.id);
    if (!contentStore.articleById(articleId)) {
      return { name: "guides" };
    }
  }

  return true;
});

export default router;
